package com.feidee.data.report.util;

import com.feidee.data.email.model.EConstant;
import com.feidee.data.report.constant.Constant;
import com.feidee.fdcommon.configuration.CustomConfiguration;
import com.feidee.fdcommon.constant.CommonConstant;
import com.feidee.fdfalcon.falcon.FalconReportService;
import org.apache.log4j.Logger;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


public class ConfigInit {

    private static Logger logger = Logger.getLogger(ConfigInit.class);
    private static int firstStart = 0;

    public void init() {

        try {
            Constant.THREAD_NUM = CustomConfiguration.getInt("thread.num", 10);
            Constant.QUEUE_SIZE = CustomConfiguration.getInt("queue.size", 500);
            Constant.MONITOR_THREAD_SLEEP_TIME = CustomConfiguration.getInt("monitor.thread.sleep", 59000);
            Constant.EXEC_THREAD_POOL_SIZE = CustomConfiguration.getInt("exec.threadpool.size", 2000);
            Constant.MONITOR_THREAD_POOL_SIZE = CustomConfiguration.getInt("monitor.threadpool.size", 200);
            Constant.TASK_RES_RETURN_URI = CustomConfiguration.getString("returnurl", "http://10.195.1.128:8111/bigdata/rest/resources/interfaces/apply/changeApp");
            Constant.EMAIL_GET_RECEIVER_URL = CustomConfiguration.getString("email.get.receiver.url");

            String printStr = CustomConfiguration.getString("print.result.sql", "");
            String[] printStrSplit = printStr.split(";");
            Constant.PRINT_RESULT_SQL.clear();
            for (String printSql : printStrSplit) {
                String[] relation = printSql.split(":");
                if (relation.length != 2) {
                    continue;
                }
                String reportKey = relation[0];
                String indexStr = relation[1];
                String[] indexs = indexStr.split(",");
                for (String index : indexs) {
                    if (Constant.PRINT_RESULT_SQL.containsKey(reportKey)) {
                        Constant.PRINT_RESULT_SQL.get(reportKey).add(index);
                    } else {
                        HashSet<String> indexSet = new HashSet<>();
                        indexSet.add(index);
                        Constant.PRINT_RESULT_SQL.put(reportKey, indexSet);
                    }
                }
            }

            String allowStr = CustomConfiguration.getString("allow.overtime.sql", "");
            String[] allowStrSplit = allowStr.split(";");
            Constant.ALLOW_OVERTIME_SQL.clear();
            for (String allowSql : allowStrSplit) {
                String[] relation = allowSql.split(":");
                if (relation.length != 2) {
                    continue;
                }
                String reportKey = relation[0];
                String indexStr = relation[1];
                String[] indexs = indexStr.split(",");
                for (String index : indexs) {
                    if (Constant.ALLOW_OVERTIME_SQL.containsKey(reportKey)) {
                        Constant.ALLOW_OVERTIME_SQL.get(reportKey).add(index);
                    } else {
                        HashSet<String> indexSet = new HashSet<>();
                        indexSet.add(index);
                        Constant.ALLOW_OVERTIME_SQL.put(reportKey, indexSet);
                    }
                }
            }

            // 初始化报表优先级高中低对应的具体数字优先级
            String customPriorityStr = CustomConfiguration.getString("custom.priority");
            String[] priorityKeyValue = customPriorityStr.split(";", -1);
            for (String keyValue : priorityKeyValue) {
                String[] keyValueArr = keyValue.split(":");
                Constant.CUSTOM_PRIORITY.put(keyValueArr[0], keyValueArr[1]);
            }
            Constant.ENV = CustomConfiguration.getString("env", "live");
            EConstant.Exception_REPORT_MAIL_GATHER_RECEIVER = CustomConfiguration.getString(
                    "exception.report.mail.gather.receiver", "kejia_zheng@suishouji.com;wei_quan@suishouji.com;wei_xu@suishouji.com;tao_ma@sui.com;bingdong_zhao@suishouji.com");
            EConstant.Exception_REPORT_MAIL_HANDLER_RECEIVER = CustomConfiguration.getString(
                    "exception.report.mail.handler.receiver", "kejia_zheng@suishouji.com;wei_quan@suishouji.com;wei_xu@suishouji.com");

            if ("test".equalsIgnoreCase(CustomConfiguration.getString("env"))) {
                CommonConstant.LOG_KAFKA_TEST = "10.200.8.13:9092,10.200.8.14:9092,10.200.8.15:9092,10.200.8.16:9092";
                CommonConstant.ZK_CONNECT_STRING_TEST = "bj4-8-centos11,bj4-8-centos12,bj4-8-centos13:2181";
                logger.info("CommonConstant.LOG_KAFKA_TEST>>>>>>>" + CommonConstant.LOG_KAFKA_TEST);
                logger.info("CommonConstant.ZK_CONNECT_STRING_TEST>>>>>>>" + CommonConstant.ZK_CONNECT_STRING_TEST);
                logger.info("CommonConstant.LOG_URL_TEST>>>>>>>" + CommonConstant.LOG_URL_TEST);
            } else {
                logger.info("CommonConstant.LOG_KAFKA_LIVE>>>>>>>" + CommonConstant.LOG_KAFKA_LIVE);
                logger.info("CommonConstant.ZK_CONNECT_STRING_LIVE>>>>>>>" + CommonConstant.ZK_CONNECT_STRING_LIVE);
                logger.info("CommonConstant.LOG_URL_LIVE>>>>>>>" + CommonConstant.LOG_URL_LIVE);
            }
            Constant.FUNNEL_REPLACE_FIELDS = new HashSet<>(Arrays.asList(
                    CustomConfiguration.getString("funnel.replace.fields", "action_tick_fuzzy_path,action_tick_path").split(",")));

            //初始化邮件发送变量
            EConstant.SEND_REPORT_MAIL_URL = CustomConfiguration.getString("report.send.mail.url",
                    "http://data.feidee.com/bigdata/rest/resources/mailSubscribe/send");
            EConstant.EMAIL_GET_DAILY_URL = CustomConfiguration.getString("email.get.daily.url",
                    "http://data.feidee.com/bigdata/rest/resources/mailreport/getData/mailDailyrep");
            EConstant.EMAIL_GET_WEEK_URL =CustomConfiguration.getString("email.get.week.url",
                    "http://data.feidee.com/bigdata/rest/resources/mailreport/getData/mailWeekrep");
            EConstant.EMAIL_QUARTZ_URL = CustomConfiguration.getString("email.quartz.url",
                    "http://data.feidee.com/feidee-data-report/email/send.do?apt=123&key=136AD6D79A084FE7");
            EConstant.EMAIL_SEND_PASSWORD = CustomConfiguration.getString("email.send.password","SuiShouWanSui123");

            Constant.CONTAIN_WAREHOUSE = new HashSet<>();
            String containWarehouse = CustomConfiguration.getString("dataResources.contain.warehouse", "");
            String[] containWarehouseArray = containWarehouse.split(";");
            for (String warehouse : containWarehouseArray) {
                Constant.CONTAIN_WAREHOUSE.add(warehouse);
            }

            Constant.FILTER_TABLE = new HashSet<>();
            String filterTable = CustomConfiguration.getString("dataResources.filter.table", "");
            String[] filterTableArray = filterTable.split(";");
            for (String table : filterTableArray) {
                Constant.FILTER_TABLE.add(table);
            }

            int sparkNum = CustomConfiguration.getInt("spark.thrift.num");

            for (int i = 1; i <= sparkNum; i++) {
                Map<String, String> conf = new HashMap<>();
                conf.put("host", CustomConfiguration.getString("ssh.host" + "_" + i, "10.200.1.13"));
                conf.put("username", CustomConfiguration.getString("ssh.username" + "_" + i, "hadoop"));
                conf.put("password", CustomConfiguration.getString("ssh.password" + "_" + i, "PjUEIIt8GlsEHaqD1X8d"));
                conf.put("cmd", CustomConfiguration.getString("ssh.reboot.cmd" + "_" + i,
                        "/data/spark_report_thrift/reboot-thriftserver.sh"));
                Constant.SPARK_THRIFT.put(i, conf);

                if (!Constant.RUNNING_SQL.keySet().contains(i)) {
                    Set<String> set = new HashSet<>();
                    Constant.RUNNING_SQL.put(i, set);
                }
            }
            Constant.SPARK_THRIFT_OVERTIME = CustomConfiguration.getLong("spark.thrift.overtime", 60);
			Constant.HIVE_RUN_OVERTIME = CustomConfiguration.getLong("hive.run.overtime", 90);

            String snappyDataRunOn36 = CustomConfiguration.getString("snappydata.run.on.36", "");
            Constant.SNAPPYDATA_RUN_ON_36.clear();
            String[] snappyDataRunOn36Split = snappyDataRunOn36.split(",");
            for (String snappyDataRunOn36String : snappyDataRunOn36Split) {
                Constant.SNAPPYDATA_RUN_ON_36.add(snappyDataRunOn36String);
            }

            Constant.IMPALA_CONNECTION = CustomConfiguration.getString("impala.jdbc.url");

            logger.info("Constant.THREAD_NUM>>>>>>>" + Constant.THREAD_NUM);
            logger.info("Constant.QUEUE_SIZE>>>>>>>" + Constant.QUEUE_SIZE);
            logger.info("Constant.MONITOR_THREAD_SLEEP_TIME>>>>>>>" + Constant.MONITOR_THREAD_SLEEP_TIME);
            logger.info("Constant.EXEC_THREAD_POOL_SIZE>>>>>>>" + Constant.EXEC_THREAD_POOL_SIZE);
            logger.info("Constant.MONITOR_THREAD_POOL_SIZE>>>>>>>" + Constant.MONITOR_THREAD_POOL_SIZE);
            logger.info("Constant.TASK_RES_RETURN_URI>>>>>>>" + Constant.TASK_RES_RETURN_URI);
            logger.info("Constant.ENV>>>>>>>" + Constant.ENV);
            logger.info("EConstant.Exception_REPORT_MAIL_GATHER_RECEIVER>>>>>>>" + EConstant.Exception_REPORT_MAIL_GATHER_RECEIVER);
            logger.info("EConstant.Exception_REPORT_MAIL_HANDLER_RECEIVER>>>>>>>" + EConstant.Exception_REPORT_MAIL_HANDLER_RECEIVER);
            logger.info("EConstant.SEND_REPORT_MAIL_URL>>>>>>>" + EConstant.SEND_REPORT_MAIL_URL);
            logger.info("EConstant.EMAIL_GET_DAILY_URL>>>>>>>" + EConstant.EMAIL_GET_DAILY_URL);
            logger.info("EConstant.EMAIL_GET_WEEK_URL>>>>>>>" + EConstant.EMAIL_GET_WEEK_URL);
            logger.info("EConstant.EMAIL_QUARTZ_URL>>>>>>>" + EConstant.EMAIL_QUARTZ_URL);
            logger.info("Constant.EMAIL_SEND_PASSWORD>>>>>>>" + EConstant.EMAIL_SEND_PASSWORD);
            logger.info("Constant.FUNNEL_REPLACE_FIELDS>>>>>>>" + Constant.FUNNEL_REPLACE_FIELDS);
            logger.info("Constant.PRINT_RESULT_SQL>>>>>>>" + Constant.PRINT_RESULT_SQL);
			logger.info("Constant.ALLOW_OVERTIME_SQL>>>>>>>" + Constant.ALLOW_OVERTIME_SQL);
            logger.info("Constant.CONTAIN_WAREHOUSE>>>>>>>" + Constant.CONTAIN_WAREHOUSE);
            logger.info("Constant.FILTER_TABLE>>>>>>>" + Constant.FILTER_TABLE);
            logger.info("Constant.SPARK_THRIFT>>>>>>>" + Constant.SPARK_THRIFT);
            logger.info("Constant.SPARK_THRIFT_OVERTIME>>>>>>>" + Constant.SPARK_THRIFT_OVERTIME);
			logger.info("Constant.HIVE_RUN_OVERTIME>>>>>>>" + Constant.HIVE_RUN_OVERTIME);
            logger.info("Constant.SNAPPYDATA_RUN_ON_36>>>>>>>" + Constant.SNAPPYDATA_RUN_ON_36);
            logger.info("Constant.IMPALA_CONNECTION>>>>>>>" + Constant.IMPALA_CONNECTION);

            initUuidIpPrefix();
            logger.info("Constant.UUID_IP_PREFIX>>>>>>>" + Constant.UUID_IP_PREFIX);

            if (0 == firstStart) {
                if ("test".equals(CustomConfiguration.getString("env"))) {
                    FalconReportService.start("data-report-test");
                } else {
                    FalconReportService.start("data-report");
                }
                firstStart = 1;
            }

        } catch (Exception e) {
            logger.error("初始化Constant异常！", e);
        } finally {
        }

    }

    /**
     * 初始化用于requestId的ip前缀
     */
    private void initUuidIpPrefix() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            Collection<InetAddress> addresses = new ArrayList<InetAddress>();

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    addresses.add(inetAddress);
                }
            }
            String ip = "";
            for (InetAddress address : addresses) {
                if (!address.isLoopbackAddress() && !address.getHostAddress().contains(":"))
                    ip = address.getHostAddress();
            }
            logger.info("ip:" + ip);
            String ip_last = ip.split("\\.")[3];
            Constant.UUID_IP_PREFIX = ip_last;
            for (int i = 0; i < 3 - ip_last.length(); i++) {
                Constant.UUID_IP_PREFIX = "0" + Constant.UUID_IP_PREFIX;
            }
        } catch (SocketException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

}
